package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	"gitee.com/go-course/go8/micro/rpc/grpc/stream/client/auth"
	"gitee.com/go-course/go8/micro/rpc/grpc/stream/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

// 其他服务器上的客户端需要来调用grpc
func main() {
	// 1. 建立网络连接, 默认情况是http2是强制要求证书的
	// grpc.WithInsecure() 已经降级
	conn, err := grpc.Dial(
		"localhost:1234",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithPerRPCCredentials(auth.NewPerRPCCredentialsImpl("admin", "123456")),
	)
	if err != nil {
		panic(err)
	}

	// 2. go-grpc插件已经生成好了grpc 的client sdk
	client := pb.NewHelloServiceClient(conn)

	// 3. 使用sdk
	stream, err := client.Channel(context.Background())

	// 3.1. 专门启动一个goroutie 用于发送请求 client stream
	go func() {
		for {
			err := stream.Send(&pb.Request{Value: "bob"})
			if err != nil {
				log.Fatal(err)
			}
			// 休息1秒
			time.Sleep(1 * time.Second)
		}
	}()

	// 3.2. 处理服务端响应
	for {
		resp, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatal(err)
		}
		fmt.Println(resp)
	}
}
